package com.globallogic.jira.gadget.servlet;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.config.ConstantsManager;
import com.atlassian.jira.issue.issuetype.IssueType;
import com.atlassian.jira.issue.link.IssueLinkType;
import com.atlassian.jira.issue.link.IssueLinkTypeManager;
import com.atlassian.jira.project.Project;
import com.atlassian.templaterenderer.TemplateRenderer;

/**
 * 
 * @author anton.pereverziev
 * 
 */
@SuppressWarnings("serial")
public class ProjectsListBuilderServlet extends HttpServlet {

	private final TemplateRenderer renderer;

	/**
	 * Servlet constructor that is auto-wired by Spring to include the following
	 * services registered in the params.
	 * 
	 * @param templateRenderer
	 */
	public ProjectsListBuilderServlet(final TemplateRenderer templateRenderer) {
		this.renderer = templateRenderer;
	}

	@Override
	protected void doGet(final HttpServletRequest req,
			final HttpServletResponse resp) throws ServletException,
			IOException {
		final String path = req.getContextPath();

		final Map<String, Object> velocityParams = new HashMap<String, Object>();
		final List<Project> allProjects = ComponentManager.getInstance()
				.getProjectManager().getProjectObjects();
		velocityParams.put("projects", allProjects);
		final ConstantsManager constantsManager = ComponentManager
				.getInstance().getConstantsManager();
		final Collection<IssueType> issueTypes = constantsManager
				.getAllIssueTypeObjects();
		velocityParams.put("issues", issueTypes);
		final IssueLinkTypeManager issueLinkTypeManager = ComponentManager
				.getComponentInstanceOfType(IssueLinkTypeManager.class);
		final Collection<IssueLinkType> linkTypes = issueLinkTypeManager
				.getIssueLinkTypes();
		velocityParams.put("linkTypes", linkTypes);
		velocityParams.put("path", path);
		resp.setContentType("text/html");
		renderer.render("project_select.vm", velocityParams, resp.getWriter());
	}

}
